package com.time.workbench.efficient.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.time.workbench.core.util.AuthUtil;
import com.time.workbench.efficient.entity.bo.Environment;
import com.time.workbench.efficient.entity.bo.EnvironmentServer;
import com.time.workbench.efficient.entity.dto.SetEnvironmentServerReq;
import com.time.workbench.efficient.mapper.EnvironmentMapper;
import com.time.workbench.efficient.mapper.EnvironmentServerMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 环境服务器管理service
 */
@Service
@RequiredArgsConstructor
public class EnvironmentServerService extends ServiceImpl<EnvironmentServerMapper, EnvironmentServer> implements IService<EnvironmentServer> {

    /**
     * 根据环境id设置服务器关系
     *
     * @param setEnvironmentServerReq
     * @param environmentId
     */
    public void setServer(SetEnvironmentServerReq setEnvironmentServerReq, Integer environmentId) {
        // 删除原来的服务器关系
        LambdaQueryWrapper<EnvironmentServer> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        remove(objectLambdaQueryWrapper.eq(EnvironmentServer::getEnvironmentId,environmentId));
        if (CollectionUtil.isNotEmpty(setEnvironmentServerReq.getServerIds())) {
            setEnvironmentServerReq.getServerIds().forEach(serverId -> {
                EnvironmentServer environmentServer = new EnvironmentServer();
                environmentServer.setEnvironmentId(environmentId);
                environmentServer.setServerId(serverId);
                environmentServer.setTenantId(AuthUtil.getTenantId());
                save(environmentServer);
            });
        }
    }

    /**
     * 获取环境所有服务器
     *
     * @param environmentId
     * @return
     */
    public List<EnvironmentServer> getByEnvironmentId(Integer environmentId) {
        return lambdaQuery().eq(EnvironmentServer::getEnvironmentId, environmentId).list();
    }
}
